Imports System.ServiceModel
Imports System.ServiceModel.Channels
Imports System.ServiceModel.Dispatcher

Namespace QMSAPIStarter.ServiceSupport

    Public Class ServiceKeyClientMessageInspector
        Implements IClientMessageInspector
        Private Const SERVICE_KEY_HTTP_HEADER As String = "X-Service-Key"

        Public Shared Property ServiceKey() As String
            Get
                Return m_ServiceKey
            End Get
            Set(ByVal value As String)
                m_ServiceKey = Value
            End Set
        End Property
        Private Shared m_ServiceKey As String

        Public Function BeforeSendRequest(ByRef request As Message, ByVal channel As IClientChannel) As Object Implements IClientMessageInspector.BeforeSendRequest
            Dim httpRequestMessageObject As Object
            If request.Properties.TryGetValue(HttpRequestMessageProperty.Name, httpRequestMessageObject) Then
                Dim httpRequestMessage As HttpRequestMessageProperty = TryCast(httpRequestMessageObject, HttpRequestMessageProperty)
                If httpRequestMessage IsNot Nothing Then
                    httpRequestMessage.Headers(SERVICE_KEY_HTTP_HEADER) = (If(ServiceKey, String.Empty))
                Else
                    httpRequestMessage = New HttpRequestMessageProperty()
                    httpRequestMessage.Headers.Add(SERVICE_KEY_HTTP_HEADER, (If(ServiceKey, String.Empty)))
                    request.Properties(HttpRequestMessageProperty.Name) = httpRequestMessage
                End If
            Else
                Dim httpRequestMessage As New HttpRequestMessageProperty()
                httpRequestMessage.Headers.Add(SERVICE_KEY_HTTP_HEADER, (If(ServiceKey, String.Empty)))
                request.Properties.Add(HttpRequestMessageProperty.Name, httpRequestMessage)
            End If
            Return Nothing
        End Function

        Public Sub AfterReceiveReply(ByRef reply As Message, ByVal correlationState As Object) Implements IClientMessageInspector.AfterReceiveReply
        End Sub
    End Class
End Namespace